package test.org.dbstar.scheduler;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import junit.framework.TestCase;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

/**
 * 带数据源的TestCase基类
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-21
 */
public abstract class DataSourceTestCase extends TestCase {
	protected BasicDataSource ds;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		ds = buildDataSource(loadProperties("src/main/configs/test.properties"));
		DatabasePopulatorUtils.execute(buildDatabasePopulator("src/main/sql/scheduler_mysql_innodb.sql"), ds);
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		ds.close();
		ds = null;
	}

	private static Properties loadProperties(String propFile) throws IOException {
		Properties properties = new Properties();
		properties.load(new FileInputStream(propFile));
		return properties;
	}

	private static DatabasePopulator buildDatabasePopulator(String sqlFile) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.setSqlScriptEncoding("utf-8");
		populator.addScript(new FileSystemResource(sqlFile));
		return populator;
	}

	private static BasicDataSource buildDataSource(Properties properties) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(properties.getProperty("config.datasource.driverClassName"));
		ds.setUrl(properties.getProperty("config.datasource.url"));
		ds.setUsername(properties.getProperty("config.datasource.username"));
		ds.setPassword(properties.getProperty("config.datasource.password"));
		return ds;
	}

}
